package com.bai.translation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

public class ExcelParser {

    public static Map<String, String> parseExcel(String filePath) throws Exception {
        Map<String, String> translations = new HashMap<>();
        try (FileInputStream fis = new FileInputStream(new File(filePath));
             Workbook workbook = WorkbookFactory.create(fis)) {
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                String chinese = row.getCell(0).getStringCellValue();
                String english = row.getCell(1).getStringCellValue();
                String code = generateMd5Code(chinese);
                translations.put(code, chinese + "=" + english);
            }
        }
        return translations;
    }

    private static String generateMd5Code(String text) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashInBytes = md.digest(text.getBytes("UTF-8"));

        StringBuilder sb = new StringBuilder();
        for (byte b : hashInBytes) {
            sb.append(String.format("%02x", b));
        }
        return "KEY_" + sb.toString().toUpperCase();
    }
}

